package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.dto.RecommendUserDto;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: cl
 * @Date: 2022/5/1 - 05 - 01
 * @Description:
 */
@Service
public class UserInfoService {

    //远程调用用户信息服务
    @DubboReference
    private UserInfoApi userInfoApi;

    //上传照片
    @Autowired
    private OssTemplate ossTemplate;

    //人脸验证
    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    //访客服务
    @DubboReference
    private VisitorsApi visitorsApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //喜欢服务
    @DubboReference
    private UserLikeApi userLikeApi;

    @Autowired
    private TanhuaService tanhuaService;

    /**
     * 保存用户信息
     *
     * @param userInfo
     */
    public void save(UserInfo userInfo) {

        userInfoApi.save(userInfo);
    }

    /**
     * 更新用户头像信息
     *
     * @param headPhoto
     * @param id
     */
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {

        //1、将头像上传到阿里云OSS
        String file = headPhoto.getOriginalFilename();//获取图片的file
        InputStream is = headPhoto.getInputStream();//获取图片的输入流
        String imgUrl = ossTemplate.upload(file, is);//上传照片并获取url

        //2、使用百度验证头像是否包含人脸
        boolean re = aipFaceTemplate.detect(imgUrl);

        //2.1如果不包含人脸，抛出异常信息
        if (!re) {
            //图像不包含人脸，抛出自定义异常
            throw new BusinessException(ErrorResult.faceError());
        } else {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(imgUrl);
            userInfoApi.update(userInfo);

        }

    }

    /**
     * 根据id查询用户信息
     *
     * @param userId
     * @return
     */
    public UserInfoVo findById(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        UserInfoVo userInfoVo = new UserInfoVo();
        //拷贝信息给vo
        BeanUtils.copyProperties(userInfo, userInfoVo);

        //把不同的属性赋值(年龄)
        if (userInfo.getAge() != null) {
            userInfoVo.setAge(userInfo.getAge().toString());
        }
        return userInfoVo;
    }

    /**
     * 修改用户信息
     *
     * @param userInfo
     */
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    /**
     * 分页查询互相喜欢、喜欢、粉丝、谁看过我
     * type:1 互相关注、2 我关注、3 粉丝、4 谁看过我
     *
     * @param type
     * @param nickname
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult get(Integer type, String nickname, Integer page, Integer pagesize) {
        List<UserVo> vos = new ArrayList<>();
        if (type == 4) {
            List<Visitors> list = visitorsApi.getAll(UserHolder.getUserId(), page, pagesize);

            RecommendUserDto recommendUserDto = new RecommendUserDto();
            recommendUserDto.setNickname(nickname);
            if (!list.isEmpty()) {
                List<Long> ids = CollUtil.getFieldValues(list, "visitorUserId", Long.class);

                Map<Long, UserInfo> map = userInfoApi.selectByIds(ids, recommendUserDto);

                for (Visitors visitors : list) {
                    UserInfo userInfo = map.get(visitors.getVisitorUserId());
                    if (userInfo != null) {
                        //4、封装vo对象并返回
                        UserVo init = UserVo.init(userInfo);
                        init.setMatchRate((int) visitors.getScore().doubleValue());
                        vos.add(init);
                    }
                }
            }
            String keys = Constants.VISITORS_USER;
            String hashKey = String.valueOf(UserHolder.getUserId());
            redisTemplate.opsForHash().put(keys, hashKey, System.currentTimeMillis() + "");
        } else if (type == 1) {

            List<UserLike> list = userLikeApi.getYouAndMe(UserHolder.getUserId(), page, pagesize);
            getUserVo(nickname, vos, list, "userId");
        } else if (type == 2) {

            List<UserLike> list = userLikeApi.getLike(UserHolder.getUserId(), page, pagesize);
            getUserVo(nickname, vos, list, "likeUserId");
        } else if (type == 3) {

            List<UserLike> list = userLikeApi.getFance(UserHolder.getUserId(), page, pagesize);
            getUserVo(nickname, vos, list, "userId");
        }


        return new PageResult(page, pagesize, 0l, vos);
    }

    /**
     * 分页查询互相喜欢、喜欢、粉丝、谁看过我(公共方法)
     *
     * @param nickname
     * @param vos
     * @param list
     */
    private void getUserVo(String nickname, List<UserVo> vos, List<UserLike> list, String id) {
        RecommendUserDto recommendUserDto = new RecommendUserDto();
        recommendUserDto.setNickname(nickname);
        if (!list.isEmpty()) {
            List<Long> ids = CollUtil.getFieldValues(list, id, Long.class);

            Map<Long, UserInfo> map = userInfoApi.selectByIds(ids, recommendUserDto);

            for (UserLike userLike : list) {
                UserInfo userInfo = null;
                if ("likeUserId".equals(id)) {
                    userInfo = map.get(userLike.getLikeUserId());
                } else {
                    userInfo = map.get(userLike.getUserId());
                }

                if (userInfo != null) {
                    //4、封装vo对象并返回
                    UserVo init = UserVo.init(userInfo);
                    init.setId(Integer.parseInt(userInfo.getId().toString()));
                    vos.add(init);
                }
            }
        }
    }

    /**
     * 获取用户喜欢、粉丝、相互喜欢的个数
     *
     * @return
     */
    public CountsVo counts() {

        Map<String, Long> map = userLikeApi.counts(UserHolder.getUserId());
        CountsVo countsVo = new CountsVo();
        countsVo.setFanCount(map.get("fanCount"));
        countsVo.setEachLoveCount(map.get("eachLoveCount"));
        countsVo.setLoveCount(map.get("loveCount"));
        return countsVo;

    }

    /**
     * 喜欢粉丝
     *
     * @param uid
     */
    public void fans(Long uid) {

        tanhuaService.love(uid);
    }

    public void unLike(Long uid) {
        tanhuaService.unLove(uid);
    }

    /**
     * 是否喜欢
     * @param uid
     * @return
     */
    public boolean alreadyLove(Long uid) {
        Boolean b = redisTemplate.opsForSet().isMember(Constants.USER_LIKE_KEY + UserHolder.getUserId(), uid.toString());

        return b;
    }
}
